package com.wjs.sync;
class Share{
    private int num=0;
    public synchronized void incr() throws InterruptedException {
        //while解决线程虚假唤醒
        while (num!=0){
            this.wait();
        }
        num++;
        System.out.println(Thread.currentThread().getName()+"::"+num);
        this.notifyAll();
    }
    public synchronized void dncr() throws InterruptedException {
        while (num!=1){
            this.wait();
        }
        num--;
        System.out.println(Thread.currentThread().getName()+"::"+num);
        this.notifyAll();
    }
}
public class ThreadDemo {
    public static void main(String[] args) {
        Share share = new Share();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    share.incr();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"aa").start();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    share.dncr();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"bb").start();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    share.incr();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"cc").start();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    share.dncr();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"dd").start();
    }
}
